﻿using System;
using System.Diagnostics;
using System.Net.Sockets;
using System.Net;

namespace Molia.NetKernel
{
    public static class MoliaSocket
    {
        private static IPAddress First()
        {
            IPAddress ip = null;
            var hostname = Dns.GetHostName();
            var ips = Dns.GetHostAddresses(hostname);
            foreach (var i in ips)
            {
                if (i.AddressFamily == AddressFamily.InterNetwork)
                {
                    ip = i;
                }
            }
            if (ip == null)
            {
                throw new Exception("请检查网络设置");
            }
            return ip;
        }
        public static Socket Default()
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            s.Bind(new IPEndPoint(First(), 0));
            Debug.WriteLine(s.LocalEndPoint);
            return s;
        }

        public static Socket Default(int port)
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                s.Bind(new IPEndPoint(First(), port));
            }
            catch(Exception e)
            {
                throw e;
            }
            Debug.WriteLine(s.LocalEndPoint);
            return s;
        }
    }
}
